﻿using System.Reflection;
using System.Web.Mvc;
using System.Web.Routing;
using Autofac;
using System.Linq;
using Autofac.Integration.Mvc;
using Inovout.Component;
using Inovout.Data.Domain;
using Microsoft.AspNet.Identity;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Owin;
using Microsoft.Owin.Security.Inovout;
using MvcSiteMapProvider.Loader;
using MvcSiteMapProvider.Xml;
using System.Web.Hosting;
using MvcSiteMapProvider.Web.Mvc;
using Microsoft.Owin.Cors;

[assembly: OwinStartup(typeof(Inovout.Web.Mvc.MvcApplication))]
namespace Inovout.Web.Mvc
{
    public class MvcApplication : WebApplication
    {

        protected override void ConfiguationAuthentication(IAppBuilder app)
        {
            app.UseCors(CorsOptions.AllowAll);
            base.ConfiguationAuthentication(app);
            if (!ComponentRegistry.IsRegistered<IApplicationConfiguration>() && this.Properties.ContainsKey("client.id") && this.Properties.ContainsKey("client.secret"))
            {
                app.UseCookieAuthentication(new CookieAuthenticationOptions
                {
                    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                    LoginPath = new PathString("/OAuthAccount/External/Inovout")
                });
                if (this.Properties.ContainsKey("client.id"))
                {
                    app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
                    if (this.Properties.ContainsKey("client.endpoint"))
                    {
                        app.UseInovoutAuthentication(this.Properties["client.id"], this.Properties["client.secret"], this.Properties["client.endpoint"], string.Empty);
                    }
                    else
                    {
                        app.UseInovoutAuthentication(this.Properties["client.id"], this.Properties["client.secret"]);
                    }
                }
            }
        }

        protected override void ConfigurationApplication(IAppBuilder app)
        {
            base.ConfigurationApplication(app);

            app.UseAutofacMvc();
            ModelBinders.Binders.DefaultBinder = new EntityModelBinder();
            ModelMetadataProviders.Current = new WidgetModelMetadataProvider();
            HtmlHelper.ClientValidationEnabled = true;
            HtmlHelper.UnobtrusiveJavaScriptEnabled = true;
            ModelValidatorProviders.Providers[ModelValidatorProviders.Providers.IndexOf(ModelValidatorProviders.Providers.Single(m => m.GetType() == typeof(DataAnnotationsModelValidatorProvider)))] = new WidgetModelValidatorProvider();
            DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(UniqueAttribute), typeof(RemoteAttributeAdapter<UniqueAttribute>));
        }

        protected override void RegisterWebComponents(ContainerBuilder builder, Assembly[] moduleAssemblies)
        {
            base.RegisterWebComponents(builder, moduleAssemblies);
            builder.RegisterControllers(moduleAssemblies);

            builder.RegisterModelBinders(typeof(MvcApplication).Assembly);
            builder.RegisterModelBinderProvider();

            builder.RegisterModule<AutofacWebTypesModule>();

            builder.RegisterSource(new ViewRegistrationSource());

            builder.RegisterFilterProvider();


            builder.RegisterModule(new MvcSiteMapProviderModule()); // Required

            builder.RegisterAssemblyTypes(moduleAssemblies)
                .Where(t => typeof(IMembershipProvider).IsAssignableFrom(t))
                .As<IMembershipProvider>().InstancePerLifetimeScope();
        }

        protected override void RegisterDependencyResolver(ILifetimeScope container)
        {
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
            ComponentRegistry.SetApplicationComponentResolver(new MvcComponentResolver());

            MvcSiteMapProvider.SiteMaps.Loader = container.Resolve<ISiteMapLoader>();

            // Check all configured .sitemap files to ensure they follow the XSD for MvcSiteMapProvider (optional)
            var validator = container.Resolve<ISiteMapXmlValidator>();
            validator.ValidateXml(HostingEnvironment.MapPath("~/Mvc.sitemap"));

            // Register the Sitemaps routes for search engines (optional)
            XmlSiteMapController.RegisterRoutes(RouteTable.Routes);

        }
        protected override void RegisterFilters()
        {
            GlobalFilters.Filters.Add(new UnhandledExceptionFilter());
        }
        protected override void RegisterRoutes()
        {
            ViewEngines.Engines.Insert(0, new MobileCapableRazorViewEngine());
            var routes = RouteTable.Routes;
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            //routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            //routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" });

            routes.MapRoute(
                  name: "GlobalDefault",
                  url: "{controller}/{action}/{id}",
                  defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
              );
        }
    }
}
